package net.lcqf.websocket.game;

import cn.hutool.json.JSONUtil;
import io.netty.channel.Channel;
import net.lcqf.websocket.server.MsgInfoPojo;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListSet;

/**
 * TODO 简易版房间管理器
 * +----------------------------------------------------------------------
 * // | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
 * // +----------------------------------------------------------------------
 * // | Copyright (c) 2021-2025 聊来 All rights reserved.
 * // +----------------------------------------------------------------------
 * // | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">apache</a> )
 * // +----------------------------------------------------------------------
 * // | @Author: 聊来 <18970881148@qq.com>
 * // +----------------------------------------------------------------------
 * // | DateTime: 2025/4/16 14:39
 * // +----------------------------------------------------------------------
 */
public class RoomManager {

    public static final ConcurrentHashMap<Integer, ConcurrentSkipListSet<Channel>> room = new ConcurrentHashMap<>();


    /**
     * 将玩家加入到指定房间
     * @param roomId 房间号
     * @param channel 消息通道
     */
    public static void addToRoom(Integer roomId, Channel channel) {
        room.computeIfAbsent(roomId, k -> new ConcurrentSkipListSet<>()).add(channel);
    }

    /**
     * 清除房间，游戏结束后清除数据
     * @param roomId 房间号
     * @param channel 消息通道
     */
    public static void removeFromRoom(Integer roomId, Channel channel) {
        if (room.containsKey(roomId)) {
            room.get(roomId).remove(channel);
            if (room.get(roomId).isEmpty()) {
                room.remove(roomId);
            }
        }
    }

    /**
     * 群发
     * @param roomId 房间号
     * @param type 消息类型
     * @param data 消息内容
     */
    public static void sendMessageToRoom(Integer roomId, Integer type, Object data) {
        MsgInfoPojo.MsgInfo response = MsgInfoPojo.MsgInfo.newBuilder()
                .setRequestType(type)
                .setData(JSONUtil.toJsonStr(data))
                .build();

        if (room.containsKey(roomId)) {
            room.get(roomId).forEach(channel -> {
                if (channel.isActive()) {
                    channel.writeAndFlush(response);
                }
            });
        }
    }
}
